package com.wiseasy.ecrsdk2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wiseasy.ecrutils.SerialPortUtils;
import com.wiseasy.ecrutils.UsbHandler;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function3;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private EditText edSendMsg;
    private BaseAdapter<String> mAdapter;
    private List<String> list = new ArrayList<>();
    private EditText edAmount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initRecycler();

    }

    private void initView() {
        edSendMsg = findViewById(R.id.ed_send_msg);
        findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initChannel();
                list.clear();
            }
        });

        findViewById(R.id.btn_disconnect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send();
            }
        });
        findViewById(R.id.btn_switch_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setUsbMode(1);
            }
        });
        findViewById(R.id.btn_switch_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setUsbMode(0);
            }
        });
        LinearLayout linearLayout = findViewById(R.id.ll_open_close);

        if ("P5".equals(Build.MODEL)) {//这里来适配不同机型的cdc打开方式不一致问题  p5早期是0 后来是1  T2不需要这步
            //打开串口是1 关闭是0
            linearLayout.setVisibility(View.VISIBLE);
        } else {
            linearLayout.setVisibility(View.GONE);
        }
    }


    private void initRecycler() {
        mRecyclerView = findViewById(R.id.recycler_receive);
        mAdapter = provideAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        mRecyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        //设置Adapter
        mRecyclerView.setAdapter(mAdapter);
    }

    private BaseAdapter<String> provideAdapter() {
        return new BaseAdapter<String>(R.layout.item_msg, new Function3<BaseAdapter.BaseViewHolder, Integer, String, Unit>() {
            @Override
            public Unit invoke(BaseAdapter.BaseViewHolder holder, Integer position, String bean) {
                ((TextView) holder.get(R.id.tv_msg)).setText(bean);
                return null;
            }
        });
    }

    private void send() {
        String content = edSendMsg.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return;
        }
        sendMessageUsb(content);
        edSendMsg.getText().clear();
        receiveMsg("Send:" + content);
    }


    private void initChannel() {
        SerialPortUtils.getInstance().initSerialPort("/dev/ttyGS0", 115200, new UsbHandler(MainActivity.this, new UsbHandler.UsbListener() {
            @Override
            public void onGetData(@NonNull String data) {
                receiveMsg(data);
            }
        }));
    }

    private void close() {
        SerialPortUtils.getInstance().closePort();
    }

    private void setUsbMode(int mode) {
        try {
            Class<?> wangPosManagerClass = Class.forName("android.os.WangPosManager");
            Object wangPosManager = wangPosManagerClass.newInstance();
            Method method = wangPosManagerClass.getMethod("setUsbMode", int.class);
            method.invoke(wangPosManager, mode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void sendMessageUsb(String msg) {
        SerialPortUtils.getInstance().onSerialPortDataWrite(msg, new UsbHandler(MainActivity.this, null));
    }

    private void receiveMsg(String msg) {
        list.add(msg);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter.addItems(list, false);
                mRecyclerView.scrollToPosition(list.size() - 1);
            }
        });
    }
}